import { TaskBase } from '../TaskBase';

/**
 * @see https://screeps-cn.gitee.io/api/#StructureSpawn.renewCreep
 */
export class TaskGetRenewed extends TaskBase {
    shouldRun(creep: Creep): boolean {
        return !creep.body.some(bp => bp.type === CLAIM) &&     // 没有 CLAIM 部件
            'structureType' in this.target &&
            this.target.structureType === STRUCTURE_SPAWN &&    // 确认目标是 spawn
            (<StructureSpawn>this.target).my;
    }
    _run(creep: Creep) {
        // 重复 renew 直到生命值达到 80% 或者 spawn 能量不足或 spawn 在生爬
        const spawn = <StructureSpawn>this.target;
        const bodySize = creep.body.length;
        const creepCost = creep.body.map(bp => BODYPART_COST[bp.type]).sum();
        const expectedEnergy = Math.ceil(creepCost / 2.5 / bodySize);   // max: 4~100
        const expectedTicksRenewed = Math.floor(600 / bodySize);        // max: 12t
        if (spawn.store.energy < expectedEnergy || spawn.spawning) {
            // 能量不足 / 在生爬
            creep.say('🚫');
            return OK;
        }
        const result = spawn.renewCreep(creep);
        if (result === OK) {
            creep.say(`🟡${expectedEnergy}✔️${expectedTicksRenewed}`);
            return creep.ticksToLive >= CREEP_LIFE_TIME * 0.8 ? OK : ERR_UNFINISHED;
        }
        else if (result === ERR_NOT_IN_RANGE) {
            return ERR_NOT_IN_RANGE;
        }
        else {
            return OK;
        }
    }
}
